﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using Tszy.Unlimited.Base.Infrastructure.Logging;

namespace Tszy.Unlimited.Base.BackgroundTasks;

/// <summary>
/// 在 BackgroundService 内使用作用域服务。
/// </summary>
internal class ScopedBackgroundService<TService> : BackgroundService where TService : IBackgroundProcessingService
{
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// 初始化后台任务。
    /// </summary>
    /// <param name="serviceProvider"></param>
    public ScopedBackgroundService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            await DoWorkAsync(stoppingToken);
        }
        catch (Exception exception)
        {
            TszyLogger.Instance.Fatal($"{GetType().Name} exception!", exception);
        }
    }

    private async Task DoWorkAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using IServiceScope scope = _serviceProvider.CreateScope();

            var scopedProcessingService = scope.ServiceProvider.GetRequiredService<TService>();
            await scopedProcessingService.DoWorkAsync(stoppingToken);
            await Task.Delay(scopedProcessingService.DelayTime, stoppingToken);
        }
    }
}